package com.zlzlib.libscan;

import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;


import java.util.Collection;
import java.util.List;

/**
 * Created by zlz on 2018/9/13.
 * 对相机的处理类
 */
public class CameraConfigManager {

    protected final int TEN_DESIRED_ZOOM = 27;
    private Context mContext;
    //相机分辨率
    private Point mCameraResolution;
    private Point mPreviewResolution;
    //当前缩放倍数
    protected int zoom_now = 0;

    CameraConfigManager(Context context) {
        mContext = context;
    }

    protected void initCameraParameters(Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        //设置自动对焦
        if (autoFocusAble(parameters)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        //获得屏幕的长宽  当前屏幕状态的长宽
        Point screenResolution = Utils.getScreenResolution(mContext);
        Point screenResolutionForCamera = new Point();
        screenResolutionForCamera.x = screenResolution.x;
        screenResolutionForCamera.y = screenResolution.y;
        //判断屏幕是竖直还是横屏
        if (Utils.isPortrait(mContext)) {
            screenResolutionForCamera.x = screenResolution.y;
            screenResolutionForCamera.y = screenResolution.x;
        }
        mPreviewResolution = getPreviewResolution(parameters, screenResolutionForCamera);
        if (Utils.isPortrait(mContext)) {
            mCameraResolution = new Point(mPreviewResolution.y, mPreviewResolution.x);
        } else {
            mCameraResolution = mPreviewResolution;
        }
        zoom_now = parameters.getZoom();
    }

    protected void setBestCameraParameters(Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(mPreviewResolution.x, mPreviewResolution.y);
        //设置方向
        camera.setDisplayOrientation(getDisplayOrientation());
        camera.setParameters(parameters);
    }

    protected Point getCameraResolution() {
        return mCameraResolution;
    }

    //开启闪光
    protected void openFlashlight(Camera camera) {
        setFlashMode(camera, true);
    }

    //关闭闪光
    protected void closeFlashlight(Camera camera) {
        setFlashMode(camera, false);
    }

    //判断是否能自动对焦
    private boolean autoFocusAble(Camera.Parameters parameters) {
        List<String> supportedFocusModes = parameters.getSupportedFocusModes();
        if (supportedFocusModes != null) {
            return supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        return false;
    }

    private Point getPreviewResolution(Camera.Parameters parameters, Point screenResolution) {
        Point previewResolution = findBestPreviewSizeValue(parameters.getSupportedPreviewSizes(), screenResolution);
        if (previewResolution == null) {
            previewResolution = new Point((screenResolution.x >> 3) << 3, (screenResolution.y >> 3) << 3);
        }
        return previewResolution;
    }

    //通过预览分辨率和当前展示的大小   筛选出最佳符合的大小
    private Point findBestPreviewSizeValue(List<Camera.Size> supportSizeList, Point screenResolution) {
        int bestX = 0;
        int bestY = 0;
        int diff = Integer.MAX_VALUE;
        for (Camera.Size previewSize : supportSizeList) {
            int newX = previewSize.width;
            int newY = previewSize.height;
            int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
            if (newDiff == 0) {
                bestX = newX;
                bestY = newY;
                break;
            } else if (newDiff < diff) {
                bestX = newX;
                bestY = newY;
                diff = newDiff;
            }
        }
        if (bestX > 0 && bestY > 0) {
            return new Point(bestX, bestY);
        }
        return null;
    }

    /**
     * 设置缩放
     *
     * @param camera
     * @param zoom
     */
    protected void setZoom(Camera camera, int zoom) {
        try {
            //判断是否能缩放
            Camera.Parameters parameters = camera.getParameters();
            if (!parameters.isZoomSupported()) {
                return;
            }
            int tenDesiredZoom = zoom;
            //获得 最大的缩放大小
            int max = parameters.getMaxZoom();
            if (zoom < 0) {
                zoom = 0;
            }
            if (zoom > max) {
                tenDesiredZoom = max;
            }
            if (zoom_now == tenDesiredZoom) {
                return;
            }
            zoom_now = tenDesiredZoom;
            parameters.setZoom(tenDesiredZoom);
            camera.setParameters(parameters);
        } catch (Exception e) {
        }
    }


    private int getDisplayOrientation() {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info);
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) {
            return 0;
        }
        Display display = wm.getDefaultDisplay();
        int rotation = display.getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }
        return result;
    }

    private void setFlashMode(Camera camera, boolean newSetting) {
        Camera.Parameters parameters = camera.getParameters();
        String flashMode;
        /** 是否支持闪光灯 */
        if (newSetting) {
            flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_TORCH, Camera.Parameters.FLASH_MODE_ON);
        } else {
            flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_OFF);
        }
        if (flashMode != null) {
            parameters.setFlashMode(flashMode);
        }
        camera.setParameters(parameters);
    }

    private String findSettableValue(Collection<String> supportedValues, String... desiredValues) {
        String result = null;
        if (supportedValues != null) {
            for (String desiredValue : desiredValues) {
                if (supportedValues.contains(desiredValue)) {
                    result = desiredValue;
                    break;
                }
            }
        }
        return result;
    }
}
